package com.lifeng.mynetty.server.tcp;

import com.lifeng.mynetty.handler.TcpServerHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.nio.charset.Charset;

/**
 * Created by lifeng
 * 2017/9/1 14:53
 */
public class TcpServerInitializer extends ChannelInitializer<SocketChannel> {
    private String charset;
    public TcpServerInitializer() {
    }

    public TcpServerInitializer(String charset) {
        this.charset = charset;
    }
    protected void initChannel(SocketChannel socketChannel) throws Exception {
        ChannelPipeline pipeline = socketChannel.pipeline();
        pipeline.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
        pipeline.addLast("frameEncoder", new LengthFieldPrepender(4));
        //pipeline.addLast("decoder", new StringDecoder(Charset.forName(charset)));
        //pipeline.addLast("encoder", new StringEncoder(Charset.forName(charset)));
        pipeline.addLast(new TcpServerHandler(charset));
    }
}
